<template>
  <div v-if="visible" class="upload-dialog-overlay" @click.self="handleClose">
    <div class="upload-dialog">
      <div class="upload-dialog-header">
        <h3 class="upload-dialog-title">{{ title }}</h3>
        <button class="upload-dialog-close" @click="handleClose">
          <svg width="16" height="16" viewBox="0 0 16 16" fill="currentColor">
            <path d="M4.646 4.646a.5.5 0 0 1 .708 0L8 7.293l2.646-2.647a.5.5 0 0 1 .708.708L8.707 8l2.647 2.646a.5.5 0 0 1-.708.708L8 8.707l-2.646 2.647a.5.5 0 0 1-.708-.708L7.293 8 4.646 5.354a.5.5 0 0 1 0-.708z"/>
          </svg>
        </button>
      </div>
      
      <div class="upload-dialog-body">
        <!-- 上传区域 -->
        <div 
          class="upload-area"
          :class="{ 'drag-over': isDragOver }"
          @click="triggerFileSelect"
          @drop.prevent="handleDrop"
          @dragover.prevent="isDragOver = true"
          @dragleave.prevent="isDragOver = false"
        >
          <input 
            ref="fileInput"
            type="file" 
            :accept="accept"
            class="upload-input"
            @change="handleFileSelect"
          />
          
          <div class="upload-icon">
            <svg width="48" height="48" viewBox="0 0 48 48" fill="none" stroke="currentColor" stroke-width="2">
              <path d="M24 16v16m-8-8h16"/>
              <rect x="8" y="8" width="32" height="32" rx="4"/>
            </svg>
          </div>
          
          <div class="upload-text">
            <p class="upload-main-text">点击或拖拽文件到此处上传</p>
            <p class="upload-sub-text">{{ acceptText }}</p>
          </div>
        </div>
        
        <!-- 预览区域 -->
        <div v-if="previewUrl" class="preview-area">
          <div class="preview-label">预览：</div>
          <div class="preview-content">
            <img v-if="uploadType === 'image'" :src="previewUrl" alt="预览" class="preview-image" />
            <video v-else-if="uploadType === 'video'" :src="previewUrl" controls class="preview-video"></video>
            <audio v-else-if="uploadType === 'audio'" :src="previewUrl" controls class="preview-audio"></audio>
          </div>
        </div>
        
        <!-- URL 输入 -->
        <div class="url-input-section">
          <div class="url-input-label">或输入 {{ uploadTypeText }} URL：</div>
          <input 
            v-model="urlInput"
            type="text"
            class="url-input"
            :placeholder="`请输入${uploadTypeText}链接地址`"
            @input="handleUrlInput"
          />
        </div>
      </div>
      
      <div class="upload-dialog-footer">
        <button class="btn btn-cancel" @click="handleClose">取消</button>
        <button 
          class="btn btn-primary" 
          :disabled="!canSubmit"
          @click="handleSubmit"
        >
          确定
        </button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, watch } from 'vue';

const props = defineProps({
  visible: { type: Boolean, default: false },
  uploadType: { 
    type: String, 
    default: 'image',
    validator: (val) => ['image', 'video', 'audio'].includes(val)
  }
});

const emit = defineEmits(['close', 'submit']);

// 文件输入引用
const fileInput = ref(null);

// 上传状态
const isDragOver = ref(false);
const selectedFile = ref(null);
const previewUrl = ref('');
const urlInput = ref('');

// 计算属性
const title = computed(() => {
  const typeMap = {
    image: '上传图片',
    video: '上传视频',
    audio: '上传音频'
  };
  return typeMap[props.uploadType] || '上传文件';
});

const accept = computed(() => {
  const acceptMap = {
    image: 'image/*',
    video: 'video/*',
    audio: 'audio/*'
  };
  return acceptMap[props.uploadType] || '*/*';
});

const acceptText = computed(() => {
  const textMap = {
    image: '支持 JPG、PNG、GIF 等图片格式',
    video: '支持 MP4、AVI、MOV 等视频格式',
    audio: '支持 MP3、WAV、OGG 等音频格式'
  };
  return textMap[props.uploadType] || '';
});

const uploadTypeText = computed(() => {
  const textMap = {
    image: '图片',
    video: '视频',
    audio: '音频'
  };
  return textMap[props.uploadType] || '文件';
});

const canSubmit = computed(() => {
  return !!selectedFile.value || !!urlInput.value.trim();
});

// 监听弹窗关闭，重置状态
watch(() => props.visible, (val) => {
  if (!val) {
    resetState();
  }
});

// 触发文件选择
const triggerFileSelect = () => {
  fileInput.value?.click();
};

// 处理文件选择
const handleFileSelect = (event) => {
  const file = event.target.files?.[0];
  if (file) {
    processFile(file);
  }
};

// 处理文件拖放
const handleDrop = (event) => {
  isDragOver.value = false;
  const file = event.dataTransfer.files?.[0];
  if (file) {
    processFile(file);
  }
};

// 处理文件
const processFile = (file) => {
  // 验证文件类型
  const typePrefix = props.uploadType;
  if (!file.type.startsWith(typePrefix)) {
    alert(`请选择${uploadTypeText.value}文件`);
    return;
  }
  
  selectedFile.value = file;
  
  // 创建预览
  const reader = new FileReader();
  reader.onload = (e) => {
    previewUrl.value = e.target.result;
  };
  reader.readAsDataURL(file);
  
  // 清空 URL 输入
  urlInput.value = '';
};

// 处理 URL 输入
const handleUrlInput = () => {
  if (urlInput.value.trim()) {
    // 清空文件选择
    selectedFile.value = null;
    previewUrl.value = urlInput.value.trim();
  } else {
    if (!selectedFile.value) {
      previewUrl.value = '';
    }
  }
};

// 提交
const handleSubmit = () => {
  if (!canSubmit.value) return;
  
  emit('submit', {
    file: selectedFile.value,
    url: urlInput.value.trim(),
    type: props.uploadType
  });
  
  handleClose();
};

// 关闭
const handleClose = () => {
  emit('close');
};

// 重置状态
const resetState = () => {
  selectedFile.value = null;
  previewUrl.value = '';
  urlInput.value = '';
  isDragOver.value = false;
  if (fileInput.value) {
    fileInput.value.value = '';
  }
};
</script>

<style scoped>
.upload-dialog-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 9999;
  animation: fadeIn 0.2s ease-in-out;
}

@keyframes fadeIn {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}

.upload-dialog {
  background: white;
  border-radius: 8px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
  width: 90%;
  max-width: 600px;
  max-height: 90vh;
  display: flex;
  flex-direction: column;
  animation: slideIn 0.2s ease-in-out;
}

@keyframes slideIn {
  from {
    transform: translateY(-20px);
    opacity: 0;
  }
  to {
    transform: translateY(0);
    opacity: 1;
  }
}

.upload-dialog-header {
  padding: 20px 24px;
  border-bottom: 1px solid #e5e7eb;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.upload-dialog-title {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #111827;
}

.upload-dialog-close {
  background: none;
  border: none;
  padding: 4px;
  cursor: pointer;
  color: #6b7280;
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.2s;
}

.upload-dialog-close:hover {
  background-color: #f3f4f6;
  color: #111827;
}

.upload-dialog-body {
  padding: 24px;
  overflow-y: auto;
  flex: 1;
}

.upload-area {
  border: 2px dashed #d1d5db;
  border-radius: 8px;
  padding: 40px 24px;
  text-align: center;
  cursor: pointer;
  transition: all 0.2s;
  background-color: #fafafa;
}

.upload-area:hover {
  border-color: #3b82f6;
  background-color: #eff6ff;
}

.upload-area.drag-over {
  border-color: #3b82f6;
  background-color: #dbeafe;
}

.upload-input {
  display: none;
}

.upload-icon {
  color: #9ca3af;
  margin-bottom: 16px;
  display: flex;
  justify-content: center;
}

.upload-text {
  color: #6b7280;
}

.upload-main-text {
  font-size: 16px;
  margin: 0 0 8px 0;
  color: #374151;
  font-weight: 500;
}

.upload-sub-text {
  font-size: 14px;
  margin: 0;
  color: #9ca3af;
}

.preview-area {
  margin-top: 24px;
  padding-top: 24px;
  border-top: 1px solid #e5e7eb;
}

.preview-label {
  font-size: 14px;
  font-weight: 500;
  color: #374151;
  margin-bottom: 12px;
}

.preview-content {
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #f9fafb;
  border-radius: 6px;
  padding: 16px;
}

.preview-image {
  max-width: 100%;
  max-height: 300px;
  border-radius: 4px;
}

.preview-video {
  max-width: 100%;
  max-height: 300px;
  border-radius: 4px;
}

.preview-audio {
  width: 100%;
}

.url-input-section {
  margin-top: 24px;
  padding-top: 24px;
  border-top: 1px solid #e5e7eb;
}

.url-input-label {
  font-size: 14px;
  font-weight: 500;
  color: #374151;
  margin-bottom: 8px;
}

.url-input {
  width: 100%;
  padding: 10px 12px;
  border: 1px solid #d1d5db;
  border-radius: 6px;
  font-size: 14px;
  transition: all 0.2s;
  box-sizing: border-box;
}

.url-input:focus {
  outline: none;
  border-color: #3b82f6;
  box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
}

.upload-dialog-footer {
  padding: 16px 24px;
  border-top: 1px solid #e5e7eb;
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

.btn {
  padding: 8px 16px;
  border-radius: 6px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s;
  border: none;
  min-width: 80px;
}

.btn-cancel {
  background-color: #ffffff;
  color: #374151;
  border: 1px solid #d1d5db;
}

.btn-cancel:hover {
  background-color: #f9fafb;
}

.btn-primary {
  background-color: #3b82f6;
  color: white;
}

.btn-primary:hover {
  background-color: #2563eb;
}

.btn-primary:disabled {
  background-color: #9ca3af;
  cursor: not-allowed;
}

.btn-primary:disabled:hover {
  background-color: #9ca3af;
}
</style>
